package com.jspxcms.plug.service.impl;

import com.jspxcms.plug.domain.UserExchange;
import com.jspxcms.plug.domain.UserFavorite;
import com.jspxcms.plug.repository.UserExchangeDao;
import com.jspxcms.plug.service.UserExchangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(readOnly = true)
public class UserExchangeServiceImpl implements UserExchangeService {

    public UserExchange findById(Integer id){
        return userExchangeDao.findById(id);
    }

    @Override
    public UserExchange save(UserExchange exchange) {
        return userExchangeDao.save(exchange);
    }

    @Override
    public boolean exists(Integer userId, Integer goodsId) {
        List<UserExchange> byUserIdAndGoodsId = userExchangeDao.findByUserIdAndGoodsId(userId, goodsId);
        return byUserIdAndGoodsId != null && byUserIdAndGoodsId.size() > 0;

    }

    @Override
    public Page<UserExchange> findByUserId(final Integer userId, final Integer state, Integer pageIndex, Integer pageSize) {
        Specification<UserExchange> spec = new Specification<UserExchange>() {
            @Override
            public Predicate toPredicate(Root<UserExchange> userExchangeRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //userFavoriteRoot = criteriaQuery.from(UserFavorite.class);
                int arrayLength = 1;
                if (userId != null) {
                    arrayLength++;
                }
                if (state != null) {
                    arrayLength++;
                }
                Predicate[] predicates = new Predicate[arrayLength];
                arrayLength = 0;
                predicates[arrayLength++] = criteriaBuilder.greaterThanOrEqualTo(userExchangeRoot.<Integer>get("id"), 0);
                if (userId != null) {
                    predicates[arrayLength++] = criteriaBuilder.equal(userExchangeRoot.get("userId"), userId);
                }
                if (state != null) {
                    predicates[arrayLength++] = criteriaBuilder.equal(userExchangeRoot.get("success"), state);
                }

                return criteriaBuilder.and(predicates);
            }
        };
        Pageable page = new PageRequest(pageIndex, pageSize);
        return userExchangeDao.findAll(spec, page);
    }

    @Override
    public void update(UserExchange bean) {
        userExchangeDao.update(bean);
    }

    @Autowired
    private UserExchangeDao userExchangeDao;
}
